<?php
/*
Plugin Name: Alimama Deluxe!
Plugin URI: http://alimama-deluxe.wordpresscn.com/
Description: 快速设置、整合 Alimama 广告到您的 WordPress 系统中，让您的广告发布更快捷！
Author: Liu Yang (iStef)
Version: 1.026
Author URI: http://blog.istef.info/
*/

define('ALIMAMA_DELUXE_TEMPLATE_FUNCTION','ad_adv');
require_once(dirname(__FILE__) . "/tiny_cache.php");
require_once(dirname(__FILE__) . "/alimama-client.php");
class Alimama_Deluxe {
	var $debugmode = false;
	var $version = "1.026";
	var $ad_table;
	var $errors;
	var $cache;
	var $use_cache = true;
	var $api;
	var $have_user = false;
	var $have_this_site = false;
	var $legency_mode = false;
	var $advance_mode = false;
	
	var $all_ad_codes;
	var $code_page_count;
	var $code_page_count_auto;
	var $plugindir;
	var $pluginurl;
	var $content_filter_time = 0;
	
	function Alimama_Deluxe() {
		global $wpdb,$table_prefix;
		$this->cache = new TinyCache;
		$this->errors = array();
		$this->all_ad_codes = array();
		$this->code_page_count = array();
		$this->code_page_count_auto = array();
		$this->plugindir = dirname(__FILE__);
		$this->pluginurl = get_bloginfo('home') . "/wp-content/plugins/alimama-deluxe";
		$this->api = new Alimama_API_Client($this->debugmode); 
		
		$wpdb->alimama_deluxe = $table_prefix . 'alimama_deluxe';
		$this->ad_table = $wpdb->alimama_deluxe;
		$this->ad_install();
		
		$this->legency_mode = get_option('alimama_deluxe_legency_mode');
		if ($this->legency_mode == 'yes') $this->legency_mode = true; else $this->legency_mode = false;
		if (!$this->legency_mode) $this->init_alimama();
		
		add_action('admin_menu',array(&$this,'mb_addmenu'));
		if (is_admin && strtolower(substr($_GET['page'],0,14)) == 'alimama-deluxe') {
			wp_enqueue_script('jquery');
			add_action('admin_head',array(&$this,'admin_head'));
		}
		add_action('widgets_init',array(&$this,'widget_ads_register'));
		add_filter('the_content',array(&$this,'content_filters'));
		add_filter('admin_footer', array(&$this,'quicktag'));
		add_action('activity_box_end', array(&$this,'dashboard'));
		
		//add_action('activate_alimama-deluxe/alimama-deluxe.php',array(&$this,'ad_install'));
		add_action('deactivate_alimama-deluxe/alimama-deluxe.php',array(&$this,'ad_uninstall'));
	}
	//==========================================================================================================
	function admin_head() {
		echo "<script type=\"text/javascript\" src=\"{$this->pluginurl}/jquery.dimensions.js\"></script>\n";
		echo "<script type=\"text/javascript\" src=\"{$this->pluginurl}/json.js\"></script>\n";
		echo "<script type=\"text/javascript\" src=\"{$this->pluginurl}/farbtastic/farbtastic.js\"></script>\n";
		echo "<link rel=\"stylesheet\" href=\"{$this->pluginurl}/alimama-deluxe.css\" type=\"text/css\" />\n";
		echo "<link rel=\"stylesheet\" href=\"{$this->pluginurl}/farbtastic/farbtastic.css\" type=\"text/css\" />\n";
	}
	function mb_addmenu() {
		add_menu_page('Alimama-Deluxe','Alimama Deluxe','manage_options','alimama-deluxe/alimama-deluxe-index.php');
		add_submenu_page('alimama-deluxe/alimama-deluxe-index.php','广告策略管理','广告策略管理','manage_options','alimama-deluxe/alimama-deluxe-strategy-manage.php');
		if (!$this->legency_mode) add_submenu_page('alimama-deluxe/alimama-deluxe-index.php','Alimama 广告管理','阿里妈妈广告管理','manage_options','alimama-deluxe/alimama-deluxe-aliad.php');
	}

	
	//===========================================================================================================	
	
	function ad_install(){

		global $wpdb;
		require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
		//require_once(ABSPATH . 'wp-admin/admin-db.php');

		$SQL = "SHOW TABLES LIKE '$this->ad_table'";
		if ($wpdb->get_var($SQL) != $this->ad_table) {
			$SQL = "CREATE TABLE `". $this->ad_table . "` (
					`ID` int(5) NOT NULL auto_increment,
					`ad_name` varchar(255) NOT NULL,
				    `ad_code` varchar(255) NOT NULL,
				    `ad_type` enum('autocontent','manualcontent','widget','manualpage') NOT NULL default 'autocontent',
				    `ad_strategy` varchar(6) NOT NULL default '1',
				    `ad_repeat_limit` int(2) NOT NULL default '1',
					`ad_article_pos` int(3) NOT NULL default '1',
					`ad_page_pos` int(2) NOT NULL default '3',
				    `ad_position` enum('top','bottom','secondpara','manualfloat','floatleft','floatright','manual') NOT NULL default 'bottom',
				    `ad_manualformat` text NOT NULL,
  				    `ad_enable` enum('enable','disable') NOT NULL default 'enable',
				    `ad_alimama_pid` varchar(255) NOT NULL,
				    `ad_style` text NOT NULL,
				    `ad_jscode` text NOT NULL,
				    PRIMARY KEY  (`ID`)
				  )";
			dbDelta($SQL);
		}
	}
	function ad_uninstall() {
		$v = get_option('alimama_deluxe_uninstall_flag');
		global $wpdb;
		$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'alimama_deluxe_uninstall_flag'");
		if ($v == 1) $wpdb->query("DROP TABLE $this->ad_table");
	}
	function ad_remove_settings($drop = false) {
		global $wpdb;
		if ($this->use_cache) $this->clear_cache();

		$wpdb->query("TRUNCATE TABLE $this->ad_table");
		$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'alimama_deluxe_%'");
		if ($drop) {
			update_option('alimama_deluxe_uninstall_flag',1);
			//$wpdb->query("DROP TABLE $this->ad_table");
		}
	}
	
	//==========================================================================================================
	function init_alimama() {
		$memberid = get_option("alimama_deluxe_memberid");
		$securitycode = get_option("alimama_deluxe_securitycode");
		
		if (empty($memberid) || empty($securitycode)) {
			$this->have_user = false;
			$this->have_this_site = false;
		} else {
			$this->have_user = true;
			if (get_option("alimama_deluxe_siteid")) {
				$this->api->init_member($memberid,$securitycode,get_option("alimama_deluxe_siteid"));
				$this->have_this_site = true;
			} else {
				$this->have_this_site = false;
				$this->api->init_member($memberid,$securitycode);
				$r = $this->api->site_info();
				if ($this->api->success) {
					$r = &$this->api->result;
					$siteurl = get_option('home');
					$siteurl = parse_url($siteurl);
					$siteurl = sprintf("%s://%s",$siteurl['scheme'],$siteurl['host']);
					if (substr($siteurl,-1,1) == "/") $siteurl = substr($siteurl,0,-1);
					$siteurl = strtolower($siteurl);
					if (isset($r[0]['siteid'])) {
						foreach ($r as $key=>$v) {
							$u = strtolower(trim($v['url']));
							if (substr($u,-1,1) == "/") $u=substr($u,0,-1);
							if ($u == $siteurl && $v['status'] != 'D') {
								$this->api->init_member(NULL,NULL,$v['siteid']);
								update_option("alimama_deluxe_siteid",$v['siteid']);
								$this->have_this_site = true;
							}
						}
					} elseif (isset($r['siteid'])) {
						$u = strtolower(trim($r['url']));
						if (substr($u,-1,1) == "/") $u=substr($u,0,-1);
						if ($u == $siteurl && $r['status'] != 'D') {
							$this->api->init_member(NULL,NULL,$r['siteid']);
							update_option("alimama_deluxe_siteid",$r['siteid']);
							$this->have_this_site = true;
						}
					} else {
						//do nothing.
					}
				}
			}
		}
		$member_name = get_option("alimama_deluxe_member_name");
		$member_password = get_option("alimama_deluxe_member_password");
		if (empty($member_name) || empty($member_password)) {
			$this->advance_mode = false;
		} else {
			$this->api->member_name=$member_name;
			$this->api->member_password = $member_password;
			$this->advance_mode = true;
		}
		
	}
	function turn_advance_mode($mode='off',$name=NULL,$password=NULL) {
		if ($mode == 'on' && !empty($name) && !empty($password)) {
			update_option("alimama_deluxe_member_name",$name);
			update_option("alimama_deluxe_member_password",$password);
			$this->advance_mode = true;
		} else {
			update_option("alimama_deluxe_member_name","");
			update_option("alimama_deluxe_member_password",'');
			$this->advance_mode = false;
		}
	}
	function set_member_info($memberid,$securitycode) {
				update_option("alimama_deluxe_memberid",$memberid);
				update_option("alimama_deluxe_securitycode",$securitycode);
				global $wpdb;
				if ($wpdb->get_var("SELECT COUNT(*) FROM $wpdb->options WHERE option_name = 'alimama_deluxe_uninstall_flag'")>0) {
					$wpdb->query("DELETE FROM $wpdb->options WHERE option_name='alimama_deluxe_uninstall_flag'");
				}
				$this->init_alimama();
				return true;
	}
	function register($logname,$passwd,$nickname,$mobile) {
		if ($this->api->register($logname,$passwd,$nickname,$mobile)) {
			if ($this->api->success) {
				$this->set_member_info($this->api->result['memberid'],$this->api->result['securityCode']);
				return array('success'=>true);
			} else {
				return array('success'=>false,'errormsg'=>$this->api->error['desc']);
			}
		} else {
			return array('success'=>false,'errormsg'=>'连接 Alimama 服务器故障，请检查服务器网络状况');
		}
	}
	function site_add($name,$url,$type,$description,$sex,$age,$income,$job,$hobby=NULL) {
		$r = $this->api->site_add($name,$url,$type,$description,$sex,$age,$income,$job,$hobby);
		if ($this->api->success) {
			$siteid = $this->api->result['siteid'];
			update_option("alimama_deluxe_siteid",$siteid);
			$this->init_alimama();
			return array('success'=>true,'siteid'=>$siteid);
		} else {
			return array('success'=>false,'errormsg'=>$this->api->error['desc']);
		}
	}
	function turn_on_legency_mode() {
		update_option('alimama_deluxe_legency_mode','yes');
	}

	//==========================================================================================================
	function ad_add_item($name,$code,$type = 'autocontent',$strategy = '1',$repeat_limit = 1,$article_pos = 1,$page_pos = 3,$position = 'bottom',$manualformat = '',$enable = 'enable',$alimama_pid="",$alimama_schemename="",$alimama_schemedetail="",$jscode="") {
		global $wpdb;
		$this->reset_errors();
		//check the name or code
		if ($wpdb->get_var("SELECT COUNT(*) FROM $this->ad_table WHERE ad_name = '$name' OR ad_code = '$code'")>0) {
			$this->raise_error(1001,'ad_add_item','Name or Code exists, please assign another');
			return false;
		} else {
			$name = str_replace("'","",strip_tags($name));
			if (strlen($name)<=0) {
				$this->raise_error(1002,'ad_add_item','Name cannot be blank');
			}
			if (preg_match("/[^0-9a-zA-Z]/",$code)) {
				$this->raise_error(1003,'ad_add_item','Only [0-9a-zA-Z]s are allowed in Code string');
			}
			$type = strtolower($type);
			if (!in_array($type,array('autocontent','manualcontent','widget','manualpage'))) {
				$type = 'autocontent';
			}
			if (!is_numeric($strategy)) {
				$strategy = '1';
			}
			$strategy = round($strategy);
			if ($strategy<1) $strategy = 1;
			$repeat_limit = intval($repeat_limit);
			if ($repeat_limit < 0) $repeat_limit = 0;
			$article_pos = (int) abs($article_pos);
			$page_pos = in_array($page_pos,array(1,2,3))?$page_pos:3;
			$position = strtolower($position);
			if (!in_array($position,array('top','bottom','secondpara','manualfloat','floatleft','floatright','manual'))) {
				$position = 'bottom';
			}
			$manualformat = str_replace("'","\'",$manualformat);
			$enable = strtolower($enable);
			if (!in_array($enable,array('enable','disable'))) {
				$enable = 'enable';
			}
			if (empty($alimama_pid)) {
				$this->raise_error(1007,'ad_add_item','您必须关联一个 Alimama 广告位');
			}
			$ad_style = array($alimama_schemename,base64_encode($alimama_schemedetail));
			$ad_style = serialize($ad_style);
			//$ad_style = str_replace("'","\'",$ad_style);
			if (empty($jscode)) {
				$this->raise_error(1008,'ad_add_item','未知错误');
			}
			$jscode = base64_encode($jscode);
			//$jscode = str_replace("'","\'",$jscode);
			if ($this->error_no()<=0) {
				$SQL = "INSERT INTO $this->ad_table 
						(ad_name,ad_code,ad_type,ad_strategy,ad_repeat_limit,ad_article_pos,ad_page_pos,ad_position,ad_manualformat,ad_enable,ad_alimama_pid,ad_style,ad_jscode)
						VALUES ('$name','$code','$type','$strategy',$repeat_limit,$article_pos,$page_pos,'$position','$manualformat','$enable','$alimama_pid','$ad_style','$jscode')";
				if ($this->use_cache) $this->clear_cache();
				$wpdb->query($SQL);
				if ($wpdb->insert_id) return true;
				else {
					$this->raise_error(1004,'ad_add_item','DB Insert ERROR');
					return false;
				}
			} else return false;
		}
	}
	function ad_update_item($id,$name = NULL,$code = NULL,$type = NULL,$strategy = NULL,$repeat_limit = NULL,$article_pos = NULL,$page_pos = NULL,$position = NULL,$manualformat = NULL,$enable = NULL,$alimama_pid = NULL,$alimama_schemename = NULL,$alimama_schemedetail = NULL,$jscode = NULL) {
		global $wpdb;
		$row = $wpdb->get_row("SELECT * FROM $this->ad_table WHERE ID = $id");
		if ($row) {
			if (is_null($name)) $name = $row->ad_name;
			if (is_null($code)) $code = $row->ad_code;
			if (is_null($type)) $type = $row->ad_type;
			if (is_null($strategy)) $strategy = $row->ad_strategy;
			if (is_null($repeat_limit)) $repeat_limit = $row->ad_repeat_limit;
			if (is_null($article_pos)) $article_pos = $row->ad_article_pos;
			if (is_null($page_pos)) $page_pos = $row->ad_page_pos;
			if (is_null($position)) $position = $row->ad_position;
			if (is_null($manualformat)) $manualformat = $row->ad_manualformat;
			if (is_null($enable)) $enable = $row->ad_enable;
			if (is_null($alimama_pid) || empty($alimama_pid)) $alimama_pid = $row->ad_alimama_pid;
				$___style = unserialize($row->ad_style);
			if (is_null($alimama_schemename)) $alimama_schemename = $___style[0];
			if (is_null($alimama_schemedetail)) $alimama_schemedetail = $___style[1];
			if (is_null($jscode) || empty($jscode)) $jscode = base64_decode($row->ad_jscode);
			
			$name = str_replace("'","",strip_tags($name));
			if (strlen($name)<=0) {
				$this->raise_error(2002,'ad_update_item','Name cannot be blank');
			}
			if (preg_match("/[^0-9a-zA-Z]/",$code)) {
				$this->raise_error(2003,'ad_update_item','Only [0-9a-zA-Z]s are allowed in Code string');
			}
			$type = strtolower($type);
			if (!in_array($type,array('autocontent','manualcontent','widget','manualpage'))) {
				$type = $row->ad_type;
			}
			if (!is_numeric($strategy)) {
				$strategy = $row->ad_strategy;
			}
			if ($strategy<1) $strategy = 1;
			$strategy = round($strategy);
			$repeat_limit = intval($repeat_limit);
			if ($repeat_limit < 0) $repeat_limit = $row->ad_repeat_limit;
			$article_pos = (int) abs($article_pos);
			$page_pos = in_array($page_pos,array(1,2,3))?$page_pos: $row->ad_page_pos;
			$position = strtolower($position);
			if (!in_array($position,array('top','bottom','secondpara','manualfloat','floatleft','floatright','manual'))) {
				$position = $row->ad_position;
			}
			$manualformat = str_replace("'","\'",$manualformat);
			$enable = strtolower($enable);
			if (!in_array($enable,array('enable','disable'))) {
				$enable = $row->ad_enable;
			}
			$ad_style = array($alimama_schemename,base64_encode($alimama_schemedetail));
			$ad_style = serialize($ad_style);
			//$ad_style = str_replace("'","\'",$ad_style);
			$jscode = stripslashes($jscode);
			$jscode = base64_encode($jscode);
			//$jscode = str_replace("'","\'",$jscode);
			//var_dump($jscode);
			if ($this->error_no()<=0) {
				$SQL = "UPDATE $this->ad_table SET
						ad_name = '$name',ad_code = '$code',ad_type = '$type',ad_strategy = '$strategy',ad_repeat_limit='$repeat_limit',ad_article_pos=$article_pos,ad_page_pos=$page_pos,ad_position='$position',ad_manualformat = '$manualformat',ad_enable='$enable',ad_alimama_pid='$alimama_pid',ad_style='$ad_style',ad_jscode='$jscode'
						WHERE ID = $id
				";
				$wpdb->query($SQL);
				if ($this->use_cache) {
					$this->clear_cache();
				}
				return true;
			} else return false;
		} else {
			$this->raise_error(2001,'ad_update_item','ID is not found');
			return false;
		}
	}
	function ad_remove_item($id) {
		global $wpdb;
		if ($this->use_cache) {
			$this->clear_cache();
		}
		
		return $wpdb->query("DELETE FROM $this->ad_table WHERE ID = $id");
	}
	
	function ad_get_strategies() {
		if ($this->legency_mode || ($this->have_user && $this->have_this_site)) {
			global $wpdb;
			return $wpdb->get_results("SELECT * FROM $this->ad_table ORDER BY ad_enable,ID ASC");
		} else return false;
	}
	//==========================================================================================================
	function get_seller_adzones($zoneid = NULL,$forcenew = false) {
		if (!$this->advance_mode || !$this->have_user || !$this->have_this_site) return false;
		$sig = "get_seller_adzones";
		if ($forcenew || !$this->use_cache || $this->cache->check($sig) != 'HIT') {
			$api = &$this->api;
			$r = $api->zone_info();
			$count = 0;
			$name_id_pairs = array();
			if ($r && $api->success) {
				$a = &$api->result;
				if (isset($a['adzoneid'])) {
					$tmp0= array();
					$tmp0[0] = $a;
					$a = $tmp0;
				}
				$this_site_id = $api->site_id;
				foreach ($a as $key=>$ad) {
					if ($ad['siteid'] != $this_site_id) {
						unset($a[$key]);
						continue;
					}
					$count++;
					$name_id_pairs[$ad['name']] = $ad['adzoneid'];
				}
			}
			if (count($name_id_pairs)) {
				$seller_adzones = $api->get_seller_adzones_detail();
				if (is_array($seller_adzones) && count($seller_adzones)) {
					foreach ($seller_adzones as $key=>$v) {
						if (in_array($key,array_keys($name_id_pairs))) {
							$seller_adzones[$key]['adzoneid'] = $name_id_pairs[$key];
						} else {
							unset($seller_adzones[$key]);
						}
					}
				}
			}
			if (isset($seller_adzones) && is_array($seller_adzones) && count($seller_adzones)) {
				if ($this->use_cache) {
					$this->cache->set($sig,$seller_adzones);
				}
			}
		} else {
			$seller_adzones = $this->cache->get($sig);
		}
		
		if (is_null($zoneid)) return $seller_adzones;
		else {
			foreach ($seller_adzones as $adzones) {
				if ($adzones['adzoneid'] == $zoneid) {
					return $adzones;
					break;
				}
			}
			return false;
		}
	}
	function get_seller_adzones_chart($size,$zoneid = NULL,$forcenew = false) {
		$zone = $this->get_seller_adzones($zoneid,$forcenew);
		if (!$zone) return false;
		
		$url = "http://chart.apis.google.com/chart?chs=$size&";
		if (is_null($zoneid)) {
			$url .= "cht=p3&chco=90c6df,ff9000&";
			$brow_str = array();
			$visit_str = array();
			$clickrate_str = array();
			foreach ($zone as $key=>$z) {
				$d = &$z['data'];
				$brow = 0; $visit = 0;
				foreach ($d as $di) {
					$brow += $di['brow'];
					$visit += $di['visit'];
				}
				$brow_str[] = $brow;
				$visit_str[] = $visit;
				$clickrate_str[$key] = round($visit/$brow*100,1);
			}
			//$datastr = "chd=t:" . implode(",",$visit_str) . "|" . implode(",",$brow_str);
			$click = array_sum($visit_str);
			$noclick = array_sum($brow_str)-$click;
			$datastr = sprintf("chd=t:%d,%d",round($noclick/($noclick+$click)*100,1),round($click/($noclick+$click)*100,1));
			$url .= $datastr . "&";
			$url .= "chl=$noclick|$click";
			
			$sum_click_rate = round($click / ($click+$noclick) * 100,1);
			$max_rate = max($clickrate_str);
			$min_rate = min($clickrate_str);
			foreach ($clickrate_str as $__k=>$__r) {
				if ($__r == $max_rate) $max_rate_key = $__k;
				if ($__r == $min_rate) $min_rate_key = $__k;
			}
			$max_rate_s = array();
			$min_rate_s = array();
			
			$ss = $this->ad_get_strategies();
			if ($ss && count($ss)) {
				foreach ($ss as $k=>$s) {
					list($mm,$memeberid,$siteid,$_adzoneid) = explode("_",$s->ad_alimama_pid);
					if ($_adzoneid == $zone[$max_rate_key]['adzoneid']) {
						$max_rate_s[] = $ss[$k];
					} elseif ($_adzoneid == $zone[$min_rate_key]['adzoneid']) {
						$min_rate_s[] = $ss[$k];
					}
				}
			}
			
			return array(
				'img' => $url,
				'total' => array(
							'browse'=>$click+$noclick,
							'click'=>$click,
							'click_rate'=>$sum_click_rate
							),
				'best' => array('name'=>$max_rate_key,'zone'=>$zone[$max_rate_key],'rate'=>$max_rate,'strategies'=>$max_rate_s),
				'worst' => array('name'=>$min_rate_key,'zone'=>$zone[$min_rate_key],'rate'=>$min_rate,'strategies'=>$min_rate_s)
			);
		} else {
			//line
			$url .= "cht=lxy&chco=90c6df,ff9000&";
			$dt = getdate();
			$today = $this->api->_yday_to_ymd($dt['year'],$dt['yday']+1);
			$fromday = $this->api->_yday_to_ymd($dt['year'],$dt['yday']-29);
			$axis_x = array();
			for ($i=1;$i<=30;$i++) $axis_x[] = $i;
			$axis_y1 = array();$axis_y2 = array();
			for ($i=$dt['yday']-29;$i<=$dt['yday']+1;$i++) {
				$dt_str = $this->api->_yday_to_ymd($dt['year'],$i);
				$found = false;
				foreach($zone['data'] as $d) {
					if ($d['date'] == $dt_str) {
						$axis_y1[] = $d['brow'];
						$axis_y2[] = $d['visit'];
						$found = true;
						break;
					}
				}
				if (!$found) {
						$axis_y1[] = 0;
						$axis_y2[] = 0;
				}
			}
			foreach ($axis_x as $key=>$value) {
				$axis_x[$key] = round($value/30 * 100,1);
			}
			$max_y = max($axis_y1)+5;
			foreach ($axis_y1 as $key=>$value) {
				$axis_y1[$key]=round($value/$max_y*100,1);
			}
			foreach ($axis_y2 as $key=>$value) {
				$axis_y2[$key]=round($value/$max_y*100,1);
			}
			$url .= "chd=t:" . implode(",",$axis_x) . "|" . implode(",",$axis_y1) . "|" . implode(",",$axis_x) . "|" . implode(",",$axis_y2) . "&";
			$url .= "chxt=x,y&";
			$url .= "chxr=0,1,30|1,0," . $max_y . "&";
			$chxl_str = array(
							$this->api->_yday_to_ymd($dt['year'],$dt['yday']-29),
							$this->api->_yday_to_ymd($dt['year'],$dt['yday']-23),
							$this->api->_yday_to_ymd($dt['year'],$dt['yday']-17),
							$this->api->_yday_to_ymd($dt['year'],$dt['yday']-11),
							$this->api->_yday_to_ymd($dt['year'],$dt['yday']-5),
							$this->api->_yday_to_ymd($dt['year'],$dt['yday']+1));
			$url .= "chxl=0:|".implode("|",$chxl_str) ."&";
			$url .= "chg=20,20,1,5";
			
			$sum_brow = 0; $sum_click = 0;
			foreach ($zone['data'] as $d) {
				$sum_brow += $d['brow'];
				$sum_click += $d['visit'];
			}
			$sum_rate = round($sum_click/$sum_brow *100,1);
			
			$zoness = array();
			$ss = $this->ad_get_strategies();
			if ($ss && count($ss)) {
				foreach ($ss as $k=>$s) {
					list($mm,$memeberid,$siteid,$_adzoneid) = explode("_",$s->ad_alimama_pid);
					if ($_adzoneid == $zone['adzoneid']) {
						$zoness[] = $ss[$k];
					}
				}
			}

			return array(
				'url' => $url,
				'brow' => $sum_brow,
				'click' => $sum_click,
				'rate' => $sum_rate,
				'zone' => $zone,
				'strategies' => $zoness
			);
		}
	}
	function clear_cache() {
		if ($this->use_cache) {
			$dir = opendir($this->cache->_cache_dir);
			while(($filename = readdir($dir)) !== false) {
				$fullname = $this->cache->_cache_dir . "/" . $filename;
				if (is_file($fullname) && substr($filename,0,15)=='alimama_deluxe_') {
					@unlink($fullname);
				}
			}
		}
	}
	function get_ad_strategy($id,$forcenew = false) {
		$sig = "get_ad_strategy_$id";
		if ($forcenew || !$this->use_cache || $this->cache->check($sig) != 'HIT') {
			global $wpdb;
			$ad = $wpdb->get_row("SELECT * FROM $this->ad_table WHERE ID = $id");
			if ($ad) {
				if ($this->use_cache) {
					$this->cache->set($sig,$ad);
				}
				return $ad;
			} else return false;
		} else {
			return $this->cache->get($sig);
		}
	}
	function get_all_filters($forcenew = false) {
		$sig = 'get_all_filters';
		if ($forcenew || !$this->use_cache || $this->cache->check($sig) != 'HIT') {
			global $wpdb;
			$rs = $wpdb->get_results("SELECT ID,ad_code,ad_type,ad_name FROM $this->ad_table WHERE ad_enable = 'enable' ORDER BY ID ASC");
			if ($rs && count($rs)) {
				$this->all_ad_codes = array();
				foreach ($rs as $r) {
					$this->all_ad_codes[] = array($r->ID,'<!--Alimama_Deluxe#'.trim($r->ad_code).'-->',$r->ad_type,$r->ad_name);
				}
				if ($this->use_cache) {
					$this->cache->set($sig,$this->all_ad_codes);
				}
				return true;
			} else return false;
		} else {
			$this->all_ad_codes = $this->cache->get($sig);
			return true;
		}
	}
	function __test_all_filters($forcenew = false) {
		if (!$this->legency_mode && (!$this->have_user || !$this->have_this_site)) return false;
		if (!is_array($this->all_ad_codes) || count($this->all_ad_codes)<1) {
			$r = $this->get_all_filters($forcenew);
		} else return true;
		if (!$r || !is_array($this->all_ad_codes) || count($this->all_ad_codes)<1) return false;
		else return true;
	}
	function wipe_out_some_filters($content,$type,$forcenew = false) {
		if (!$this->__test_all_filters($forcenew)) return false;
		$rep_array = array();
		foreach ($this->all_ad_codes as $c) {
			if ($c[2]==$type) $rep_array[] = $c[1];
		}
		return str_replace($rep_array,"",$content);
	}
	function code2ad($code,$forcenew = false) {
		if (!$this->__test_all_filters($forcenew)) return NULL;
		if (preg_match("/<!\-\-Alimama_Deluxe#(.+?)\-\->/",$code,$m)) {
			$code = $m[1];
		} else {
			//do nothing
		}
		$sig = "Alimama Deluxe Code: $code";
		if ($forcenew || !$this->use_cache || $this->cache->check($sig) != 'HIT') {
			global $wpdb;
			$ad_info = $wpdb->get_row("SELECT * FROM $this->ad_table WHERE ad_code = '$code'");
			if (!$ad_info) return NULL;
			if ($ad_info->ad_type == 'autocontent' || $ad_info->ad_type == 'manualcontent') switch ($ad_info->ad_position) {
				case 'top':
				case 'bottom':
				case 'secondpara':
				case 'manualfloat':
					$format = '<div id="alimama-deluxe-ad-'.$code.'" style="text-align:center">%code%</div>';
					break;
				case 'floatleft':
					$format = '<div id="alimama-deluxe-ad-'.$code.'" style="float:left;margin: 0 5px 5px 0">%code%</div>';
					break;
				case 'floatright':
					$format = '<div id="alimama-deluxe-ad-'.$code.'" style="float:right;margin: 0 0 5px 5px">%code%</div>';
					break;
				case 'manual':
					$format = $ad_info->ad_manualformat;
					break;
			}
			if ($ad_info->ad_type == 'widget') $format = '<span id="alimama-deluxe-ad-'.$code.'" style="text-align:center;">%code%</span>';
			if ($ad_info->ad_type == 'manualpage') $format = $ad_info->ad_manualformat;
			// retrive the Alimama's Advertise code
			$alimama_adv_code = stripslashes(base64_decode($ad_info->ad_jscode));
			$ad_out = str_replace("%code%",$alimama_adv_code,$format);
			if ($this->use_cache) {
				$this->cache->set($sig,$ad_out);
			}
			return $ad_out;
		} else {
			return $this->cache->get($sig)."<!-- from cache -->";
		}
	}
	function page_filter($code,$forcenew = false) {
		if (!preg_match("/<!\-\-Alimama_Deluxe#(.+?)\-\->/",$code,$m)) {
			return false;
		}
		if (!$this->__test_all_filters($forcenew)) return false;
		foreach ($this->all_ad_codes as $c) {
			if ($c[1]==$code) {
				if ($c[2] == 'manualpage') return $this->code2ad($code);
				break;
			}
		}
		return false;
	}
	function code_page_count_ope($code,$ope = '++',$auto = '') {
		$init = 0;
		if ($auto == 'auto') $obj = &$this->code_page_count_auto;
		else $obj = &$this->code_page_count;
		if (array_key_exists($code,$obj)) {
			switch ($ope) {
				case '++':
					$obj[$code]++;
					break;
				case 'reset':
					$obj[$code] = 0;
					break;
			}
		} else {
			switch ($ope) {
				case '++':
					$obj[$code] = 1;
					break;
				case 'reset':
					$obj[$code] = 0;
					break;
			}
		}
	}
	function content_filters($text) {
		if (is_feed()) return $text;
		$forcenew = false;
		if (!$this->__test_all_filters($forcenew)) return $text;
		$this->content_filter_time++;
		//Dealing with manual code first
		$manualcodes = array();
		foreach ($this->all_ad_codes as $c) {
			if ($c[2]=='manualcontent') {
				$manualcodes[] = array($c[1],$this->code2ad($c[1]),$this->get_ad_strategy($c[0],$forcenew));
			}
		}
		if (count($manualcodes)) {
			$pos = 0;
			settype($pos,"integer");
			while ($pos !== false) {
				$pos = strpos($text,'<!--Alimama_Deluxe#',$pos);
				if ($pos !== false) {
					$found = NULL;
					foreach($manualcodes as $mc) {
						if (substr($text,$pos,strlen($mc[0])) == $mc[0]) {
							$found = $mc;
							$this->code_page_count_ope($mc[0],'++');
							break;
						}
					}
					if (is_array($found)) {
						$found[2]->ad_repeat_limit = 1; //alimama
						if ($this->code_page_count[$found[0]] <= $found[2]->ad_repeat_limit || $found[2]->ad_repeat_limit == 0) {
							$text = substr($text,0,$pos) . $found[1] . substr($text,$pos+strlen($found[0]));
							$pos += strlen($found[1]);
						} else {
							$pos += strlen($found[0]);
						}
						
					} else $pos++;
					if ($pos >= strlen($text)) {
						$pos = false;
						settype($pos,'boolean');
					}
				}
			}
		}
		
		//Now Dealing with Autoconent advertisements;
		$autocodes = array();
		foreach ($this->all_ad_codes as $c) {
			if ($c[2]=='autocontent') {
				$autocodes[] = array($c[1],$this->code2ad($c[1]),$this->get_ad_strategy($c[0],$forcenew));
			}
		}
		if (count($autocodes)) {
			foreach ($autocodes as $ac) {
				if ($ac[2]->ad_article_pos != $this->content_filter_time) {
					continue;
				}
				if ($ac[2]->ad_article_pos == 1) {
					if ($ac[2]->ad_page_pos == 1) {
						if (is_single() || is_page()) continue;
					} elseif ($ac[2]->ad_page_pos == 2) {
						if (!is_single() && !is_page()) continue;
					}
				}
				//frequency
				if (!isset($this->code_page_count[$ac[0]])) $this->code_page_count_ope($ac[0],'reset');
				if (!isset($this->code_page_count_auto[$ac[0]])) $this->code_page_count_ope($ac[0],'reset','auto');
				$ac[2]->ad_repeat_limit = 1; //alimama only allows ads show once a page.
				if (($ac[2]->ad_repeat_limit == 0 || $this->code_page_count[$ac[0]]<$ac[2]->ad_repeat_limit) && ($this->code_page_count_auto[$ac[0]] % $ac[2]->ad_strategy == 0)) {
					switch ($ac[2]->ad_position) {
						case 'top':
						case 'floatleft':
						case 'floatright':
							$text = $ac[1] . $text;
							break;
						case 'bottom':
							$text .= $ac[1];
							break;
						case 'secondpara':
							$p_pos = strpos($text,'</p>');
							if ($p_pos !== false) {
								$text = substr($text,0,$p_pos+strlen("</p>")) . $ac[1] . substr($text,$p_pos+strlen("</p>"));
							} else {
								$p_pos = strpos($text,"\n\n");
								if ($p_pos !== false) {
								} else {
									$text .= $ac[1];
								}
							}
							break;
					}
					$this->code_page_count_ope($ac[0],'++');
				}
				$this->code_page_count_ope($ac[0],'++','auto');
			}
		}
		return $text;
	}

	//widget////////////////////////////////////////////////////////////////////////////////////////////////////
	function widget_ads($args, $number = 1) {
		extract($args);
		$options = get_option('alimama_deluxe_widget_ads');
		$title = $options[$number]['title'];
		$text = $options[$number]['adids'];
		if (empty($title)) $title = "Alimama Deluxe 广告";
		?>
			<?php echo $before_widget; ?>
				<?php if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?>
				<div class="alimama-deluxe-widget"><?php
					$out = "";
					if (is_array($text) && count($text)) foreach ($text as $ad) {
						$ad_strategy = $this->get_ad_strategy($ad);
						if ($ad_strategy) $out .= (empty($out)?"":"&nbsp;") . $this->code2ad($ad_strategy->ad_code);
					}
					echo $out;
				?></div>
				<?php echo $after_widget; ?>
		<?php
	}

	function widget_ads_control($number) {
		$options = $newoptions = get_option('alimama_deluxe_widget_ads');
		if ( !is_array($options) )
			$options = $newoptions = array();
		if ( $_POST["alimama-deluxe-ads-submit-$number"] ) {
			$newoptions[$number]['title'] = strip_tags(stripslashes($_POST["alimama-deluxe-ads-title-$number"]));
			$newoptions[$number]['adids'] = $_POST["alimama-deluxe-ads-adids-{$number}"];
		}
		if ( $options != $newoptions ) {
			$options = $newoptions;
			update_option('alimama_deluxe_widget_ads', $options);
		}
		$title = attribute_escape($options[$number]['title']);
		$adids = $options[$number]['adids'];
		?>
			<p><label>标题：</label><input style="width: 400px;" id="text-title-<?php echo $number; ?>" name="alimama-deluxe-ads-title-<?php echo $number; ?>" type="text" value="<?php echo $title; ?>" /></p>
			<p><label>请选择要显示的广告：(按住 Ctrl 或 Shift 可多选)</label><br />
				<select style="width: 450px; height: 260px;" id="alimama-deluxe-ads-adids-<?php echo $number;?>" name="alimama-deluxe-ads-adids-<?php echo $number;?>[]" multiple="multiple">
				<?php
					$this->__test_all_filters($forcenew);
					foreach ($this->all_ad_codes as $c) {
						if ($c[2]!='widget') continue;
						echo sprintf('<option value="%d"%s>%s</option>',$c[0],(in_array($c[0],$adids)?" selected":""),$c[3]);
					}
				?>
				</select>
			</p>
			<input type="hidden" id="alimama-deluxe-ads-submit-<?php echo "$number"; ?>" name="alimama-deluxe-ads-submit-<?php echo "$number"; ?>" value="1" />
		<?php
	}

	function widget_ads_setup() {
		$options = $newoptions = get_option('alimama_deluxe_widget_ads');
		if ( isset($_POST['alimama-deluxe-ads-number-submit']) ) {
			$number = (int) $_POST['alimama-deluxe-ads-number'];
			if ( $number > 9 ) $number = 9;
			if ( $number < 1 ) $number = 1;
			$newoptions['number'] = $number;
		}
		if ( $options != $newoptions ) {
			$options = $newoptions;
			update_option('alimama_deluxe_widget_ads', $options);
			$this->widget_ads_register($options['number']);
		}
	}

	function widget_ads_page() {
		$options = $newoptions = get_option('alimama_deluxe_widget_ads');
		?>
		<div class="wrap">
			<form method="POST">
				<h2><?php _e('Alimama Deluxe Advertisement Widgets'); ?></h2>
				<?php
					$this->__test_all_filters($forcenew);
					$no_widget = true;
					foreach ($this->all_ad_codes as $c) {
						if ($c[2]!='widget') continue;
						$no_widget = false;
						break;
					}
					if ($no_widget) { ?>
					<p>您当前没有激活的 Widget 广告，请在<a href="admin.php?page=alimama-deluxe/alimama-deluxe-strategy-manage.php">管理页面</a>中激活或添加一些。</p>
					<?php } else { ?>
					<p style="line-height: 30px;">您想显示几个广告单元：
					<select id="alimama-deluxe-ads-number" name="alimama-deluxe-ads-number" value="<?php echo $options['number']; ?>">
					<?php for ( $i = 1; $i < 10; ++$i ) echo "<option value='$i' ".($options['number']==$i ? "selected='selected'" : '').">$i</option>"; ?>
					</select>
					<span class="submit"><input type="submit" name="alimama-deluxe-ads-number-submit" id="alimama-deluxe-ads-number-submit" value="<?php echo attribute_escape(__('Save')); ?>" /></span></p>
					<?php } ?>
			</form>
		</div>
		<?php
	}

	function widget_ads_register() {
		$options = get_option('alimama_deluxe_widget_ads');
		$number = $options['number'];
		if ( $number < 1 ) $number = 1;
		if ( $number > 9 ) $number = 9;
		$dims = array('width' => 460, 'height' => 350);
		$class = array('classname' => 'widget_ads');

		$this->__test_all_filters($forcenew);
		$no_widget = true;
		foreach ($this->all_ad_codes as $c) {
			if ($c[2]!='widget') continue;
			$no_widget = false;
			break;
		}
		
		if (!$no_widget) for ($i = 1; $i <= 9; $i++) {
			$name = sprintf(__('Alimama Deluxe AD-%d'), $i);
			$id = "alimama-deluxe-ads-$i"; // Never never never translate an id
			wp_register_sidebar_widget($id, $name, $i <= $number ? array(&$this,'widget_ads') : /* unregister */ '', $class, $i);
			wp_register_widget_control($id, $name, $i <= $number ? array(&$this,'widget_ads_control') : /* unregister */ '', $dims, $i);
		}
		add_action('sidebar_admin_setup', array(&$this,'widget_ads_setup'));
		add_action('sidebar_admin_page', array(&$this,'widget_ads_page'));
	}
	
	//==========================================================================================================
	function dashboard() {
		?>
			<div>
				<h3>Alimama Deluxe</h3>
	<ul>
	<?php if (!$this->have_user || !$this->have_this_site) { ?>
		<li>您尚未完成 Alimama Deluxe 插件的初始化，请到<a href="admin.php?page=alimama-deluxe/alimama-deluxe-index.php">插件页面</a>中补全必须的信息。</li>
	<?php } else { ?>
		<li>您当前的站点已经关联到 Alimama 帐号中。</li>
		<?php
			$rows = $this->ad_get_strategies();
			if (!$rows) { ?>
			<li><span style="color:red">您的站点尚未设置任何广告策略，请<a href="admin.php?page=alimama-deluxe/alimama-deluxe-strategy-manage.php&a=add">添加</a>一些！</span></li>
			<?php } else {
				$enable = 0;
				foreach ($rows as $r) {
					if ($r->ad_enable == 'enable') $enable++;
				}
			?>
			<li>您共设置了 <?php echo count($rows);?> 条广告策略，<?php if ($enable) {?>其中 <?php echo $enable;?> 个正在运行。<?php } else { ?>但是都没有在运行<?php } ?>
			<?php
			}
		}
		?>
	</ul>
				
			</div>
		<?php
	}
	//==========================================================================================================
	function quicktag() {
		$forcenew = false;
		if (!$this->__test_all_filters($forcenew)) return $text;
		$this->content_filter_time++;
		//Dealing with manual code first
		$manualcodes = array();
		foreach ($this->all_ad_codes as $c) {
			if ($c[2]=='manualcontent') {
				$manualcodes[] = array($c[1],$this->code2ad($c[1]),$this->get_ad_strategy($c[0],$forcenew));
			}
		}
		if (count($manualcodes)) {
		
		?>
		<script type="text/javascript">
		if(alimama_deluxe_toolbar = document.getElementById("ed_toolbar")){
			var alimama_deluxe_button_nr = edButtons.length;
			<?php $__i = 0; foreach ($manualcodes as $_mc) { ?>
			edButtons[alimama_deluxe_button_nr+<?php echo $__i;?>] = new edButton('alimama_deluxe_button_<?php echo $__i;?>','AD#<?php echo $_mc[2]->ad_name;?>','<?php echo $_mc[0];?>', '','', -1);
			var alimama_deluxe_button_<?php echo $__i;?> = alimama_deluxe_toolbar.lastChild;
			while (alimama_deluxe_button_<?php echo $__i;?>.nodeType != 1){
				alimama_deluxe_button_<?php echo $__i;?> = alimama_deluxe_button_<?php echo $__i;?>.previousSibling;
			}
			alimama_deluxe_button_<?php echo $__i;?> = alimama_deluxe_button_<?php echo $__i;?>.cloneNode(true);
			alimama_deluxe_toolbar.appendChild(alimama_deluxe_button_<?php echo $__i;?>);
			alimama_deluxe_button_<?php echo $__i;?>.value = 'AD#<?php echo $_mc[2]->ad_name;?>';
			alimama_deluxe_button_<?php echo $__i;?>.title = alimama_deluxe_button_nr+<?php echo $__i;?>;
			alimama_deluxe_button_<?php echo $__i;?>.onclick = function () {edInsertTag(edCanvas, parseInt(this.title));}
			alimama_deluxe_button_<?php echo $__i;?>.id = "alimama_deluxe_button_<?php echo $__i;?>";
			<?php $__i++; } ?>
		}
		</script>
		<?php
		}
	}


	
	
	//==========================================================================================================
	/*
		CODE	FUNC				Description
		-----------------------------------------------------
		1001	ad_add_item			name or code is exist.
		1002	ad_add_item			name cannot be blank.
		1003	ad_add_item			Only [0-9a-zA-Z]s are allowed in Code string
		
	*/
	function raise_error($code,$func,$str){
		$this->errors[] = array($code,$func,$str);
	}
	function error_no() {
		return count($this->errors);
	}
	function get_last_error() {
		if ($this->error_no()>0) {
			return $this->errors[count($this->errors)-1];
		} else return false;
	}
	function reset_errors() {
		$this->errors = array();
	}
} //End of Class: Alimama_Deluxe
$alimama_deluxe = new Alimama_Deluxe;
function ad_adv($code) {
	global $alimama_deluxe;
	$r = $alimama_deluxe->code2ad($code);
	if (!is_null($r)) echo $r;
}
//-----------------------------------------------------------------------
?>